<template>
    <view class="tabs">
        <!-- 标签栏 -->
        <view v-for="tab in tabs" :key="tab.value" :class="['tab', { active: currentTab === tab.value }]"
              @click="switchTab(tab.value)">
            {{ tab.label }}
        </view>
    </view>
    <view class="content">
        <!-- 金额显示区域 -->
        <view class="balance-container">
            <view class="balance-item">
                <text class="balance-label">全部金额:</text>
                <text class="balance-amount">{{ totalAmount }}元</text>
            </view>
            <view class="balance-item">
                <text class="balance-label">欠款:</text>
                <text class="balance-amount">{{ totalDebt }}元</text>
            </view>
        </view>
        <!-- 各个Tab内容 -->
        <view v-if="currentTab === 'all'">
            <view v-if="debts.length === 0 && repaidBills.length === 0 && pendingBills.length === 0">
                暂无账单
            </view>
            <view v-else>
                <view v-for="(item, index) in [...debts, ...repaidBills, ...pendingBills]" :key="index" class="debt-item">
                    <view class="debt-info">
                        <view class="product-details">
                            <view>商品名称: {{ item.id }}</view>
                            <view>日期: {{ item.createtime }}</view>
                            <view>欠款总金额¥: {{ item.price }}</view>
                        </view>
                    </view>
                    <view class="debt-paystate">
                        <text :class="['paystate', getpaystateClass(item.paystate)]">{{ getpaystateText(item.paystate) }}</text>
                    </view>
                </view>
            </view>
        </view>

        <view v-if="currentTab === 'pending'">
            <view v-if="pendingBills.length === 0">暂无待审核账单</view>
            <view v-else>
                <view v-for="(item, index) in pendingBills" :key="index" class="debt-item">
                    <view class="debt-info">
                        <view class="product-details">
                            <view>商品名称: {{ item.id }}</view>
                            <view>日期: {{ item.createtime }}</view>
                         <!--   <view>订单状态: {{ item.status }}</view> -->
                            <view>欠款总金额¥: {{ item.price }}</view>
                        </view>
                    </view>
                    <view class="debt-paystate">
                        <text :class="['paystate', getpaystateClass(item.paystate)]">{{getpaystateText( item.paystate) }}</text>
                    </view>
                </view>
            </view>
        </view>

        <!-- 已还款账单显示区域 -->
        <view v-if="currentTab === 'repaid'">
            <view v-if="repaidBills && repaidBills.length === 0">暂无已还款账单</view>
            <view v-else>
                <view v-for="(item, index) in repaidBills" :key="index" class="debt-item">
                    <view class="debt-info">
                        <view class="product-details">
                            <view>商品名称: {{ item.id }}</view>
                            <view>日期: {{ item.createtime }}</view>
                 <!--           <view>订单状态: {{ item.status }}</view> -->
                            <view>欠款总金额¥: {{ item.price }}</view>
                        </view>
                    </view>
                    <view class="debt-paystate">
                        <text :class="['paystate', getpaystateClass(item.paystate)]">{{ getpaystateText(item.paystate) }}</text>
                    </view>
                </view>
            </view>
        </view>

       <view v-if="currentTab === 'debt'">
		   <view v-if="debts.length === 0">暂无欠款账单</view>
          <!-- <view v-if="debts &&debts.length === undefined">暂无欠款账单</view> -->
           <view v-else>
               <view v-for="(debt, index) in debts" :key="index" class="debt-item">
                   <view class="debt-info">
                       <view class="product-details">
                           <view>账单编号: {{ debt.id }}</view>
                           <view>日期: {{ debt.createtime }}</view>
                    <!--       <view>实际支付金额: {{ debt.realpay }}</view> -->
                           <view>欠款总金额¥: {{ debt.price }}</view>
                       </view>
                   </view>
                   <view class="debt-paystate">
                       <text :class="['paystate', getpaystateClass(debt.paystate)]">{{ getpaystateText(debt.paystate) }}</text>
                   </view>
                   <!-- 还款按钮 -->
                   <button v-if="debt.paystate === '0'" @click="repay(debt.id)">还款</button>
               </view>
           </view>
       </view>

    </view>
</template>
<script setup>
    import { ref, computed, onMounted } from 'vue';
    import {http} from '/until/request.js'	
    import { onLoad,} from "@dcloudio/uni-app"
    const currentTab = ref('all'); // 当前选中的Tab
    const debts = ref([]);/* 欠款账单数据 */
    const repaidBills = ref([]); // 已还款账单
    const pendingBills = ref([]); // 待审核账单
    const tabs = ref([{
            label: '全部',
            value: 'all'
        },
        {
            label: '欠款',
            value: 'debt'
        },
		{
		    label: '审核中',
		    value: 'pending'
		},
        {
            label: '已还款',
            value: 'repaid'
        }
       
    ]);
    const userid = ref(null);
	
    // 获取用户ID
    onLoad((id) => {
        userid.value = id.userId;
		console.log(userid.value);
        fetchBills(userid.value);
    });
	
// 还款方法，接收账单 id
const repay = async (debtId) => {
    console.log("尝试还款的账单 ID:", debtId);
	// 显示确认弹框
	    uni.showModal({
	        title: '还款确认',
	        content: `确定要还款账单编号为 ${debtId} 的欠款吗？`,
	        success: async (res) => {
	            if (res.confirm) {
	                console.log('用户点击确定');
	
	                // 更新账单状态为 "审核中"
	                try {
	                    const response = await http({
	                        url: "/orders/updatePaystate/" + debtId,
	                        method: 'POST',
	                        data: {
	                            debtId: debtId,
	                            paystate: '2'
	                        }
	                    });
	                    console.log('还款请求成功:', response);
	
	                    // 隐藏“正在还款”的提示
	                    uni.hideToast();
	
	                    // 显示“还款成功”的提示
	                    uni.showToast({
	                        title: '还款成功',
	                        icon: 'success',
	                        duration: 2000
	                    });
	
	                    // 成功后刷新账单数据
	                    await fetchBills(userid.value);
	                } catch (error) {
	                    console.error("还款失败", error);
	
	                    // 隐藏“正在还款”的提示
	                    uni.hideToast();
	
	                    // 显示“还款失败”的提示
	                    uni.showToast({
	                        title: '还款失败',
	                        icon: 'none',
	                        duration: 2000
	                    });
	                }
	            } else if (res.cancel) {
	                console.log('用户点击取消');
	
	                // 隐藏“正在还款”的提示
	                uni.hideToast();
	            }
	        }
	    });
	};
	
	//上传图片
    // // 显示确认弹框
    // uni.showModal({
    //     title: '还款确认',
    //     content: `确定要还款账单编号为 ${debtId} 的欠款吗？`,
    //     success: async (res) => {
    //         if (res.confirm) {
    //             console.log('用户点击确定');

    //             // 选择图片
    //             uni.chooseImage({
    //                 count: 1, // 限制上传 1 张图片
    //                 sizeType: ['compressed'], // 使用压缩图片
    //                 sourceType: ['album', 'camera'], // 从相册或拍照中选择
    //                 success: async (chooseResult) => {
    //                     const filePath = chooseResult.tempFilePaths[0];
    //                     console.log('选择的图片路径:', filePath);

    //                     // 上传图片到服务器
    //                     uni.uploadFile({
    //                         url: 'https://yourserver.com/upload', // 替换为实际上传图片的服务器地址
    //                         filePath,
    //                         name: 'file', // 文件对应的字段名
    //                         formData: {
    //                             debtId: debtId
    //                         },
    //                         success: async (uploadRes) => {
    //                             console.log('图片上传成功:', uploadRes);

    //                             // 更新账单状态为 "审核中"
    //                             try {
    //                                 const response = await http({
    //                                     url: "/orders/updatePaystate/" + debtId,
    //                                     method: 'POST',
    //                                     data: {
    //                                         debtId: debtId,
    //                                         paystate: '2'
    //                                     }
    //                                 });
    //                                 console.log('还款请求成功:', response);
				// 					// uni.showToast({
				// 					// 	title:'还款中',
				// 					// 	icon:'loading',
				// 					// 	duration:2000
				// 					// })
				// 					uni.showToast({
				// 						title:'还款成功',
				// 						icon:'success',
				// 						duration:2000
				// 					})
    //                                 // 成功后刷新账单数据
    //                                 await fetchBills(userid.value);
    //                             } catch (error) {
    //                                 console.error("还款失败", error);
    //                             }
    //                         },
    //                         fail: (uploadError) => {
    //                             console.error('图片上传失败:', uploadError);
    //                         }
    //                     });
    //                 },
    //                 fail: (chooseError) => {
    //                     console.error('选择图片失败:', chooseError);
    //                 }
    //             });
    //         } else if (res.cancel) {
    //             console.log('用户点击取消');
    //         }
    //     }
    // });
// };


    const fetchBills = async (userId) => {
        try {
            const response = await http({
                url: "/orders/selectbyid/"+userId,
                method: 'POST',
            });
			data: {
			    userId: userId // 添加请求体
			}
            const allBills = response.data || [];
            debts.value = allBills.filter(item => item.paystate !== '1' && item.paystate !== '2');
            repaidBills.value = allBills.filter(item => item.paystate === '1');
            pendingBills.value = allBills.filter(item => item.paystate === '2'); // 可能的待审核账单状态
        } catch (error) {
            console.error("请求失败", error);
        }
    };
    const totalAmount = computed(() => {
        return [...debts.value, ...repaidBills.value].reduce((total, bill) => total + (bill.price || 0), 0);
    });
    const totalDebt = computed(() => {
        return debts.value.reduce((total, debt) => total + (debt.price || 0), 0);
    });

    const getpaystateClass = (paystate) => {
        const paystateMap = {
            '0': 'unpaid',
            '1': 'repaid',
            '2': 'pending'
        };
        return paystateMap[paystate] || 'unpaid';
    };
	const getpaystateText = (paystate) => {
	    const paystateTextMap = {
	        "0": '待支付',
	        "1": '已还款',
	        "2": '审核中',
	    };
	    return paystateTextMap[paystate] || '审核不通过';
	};
    const switchTab = (tab) => {
        currentTab.value = tab;
    };
</script>
<style lang="scss">
	.tabs {
	    display: flex;
	    justify-content: space-around;
	    background: #f5f7fa;
	    border-bottom: 2rpx solid #ddd;
	    position: relative;
	}
	
	.tab {
	    flex: 1;
	    text-align: center;
	    padding: 20rpx 0;
	    font-size: 30rpx;
	    font-weight: bold;
	    color: #666;
	    cursor: pointer;
	    position: relative;
	}
	
	.tab.active {
	    color: #007aff;
	    font-weight: bold;
	}
	
	.tab.active::after {
	    content: '';
	    position: absolute;
	    left: 0;
	    right: 0;
	    bottom: 0;
	    height: 4rpx;
	    background: #007aff;
	    margin: auto;
	}
.content {
    padding: 40rpx;
    background: #f9fafc;
    border-radius: 16rpx;
    box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.1);
    margin-top: 20rpx;
}

.balance-container {
    background: linear-gradient(90deg, #e3f2fd, #bbdefb);
    padding: 30rpx;
    border-radius: 16rpx;
    margin-bottom: 30rpx;
    box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.1);
}

.balance-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20rpx;
}

.balance-label {
    font-size: 28rpx;
    color: #333;
    font-weight: bold;
}

.balance-amount {
    font-size: 34rpx;
    color: #1e88e5;
    font-weight: bold;
}

.debt-item {
    background: #ffffff;
    border: 1rpx solid #ddd;
    border-radius: 16rpx;
    margin-bottom: 30rpx;
    padding: 20rpx 30rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
    transition: all 0.3s ease;
}

.debt-item:hover {
    transform: scale(1.02);
    box-shadow: 0 6rpx 18rpx rgba(0, 0, 0, 0.1);
}

.product-details {
    flex: 1;
    padding-right: 20rpx;
}

.product-details view {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 10rpx;
    line-height: 40rpx;
    word-wrap: break-word;
}

.product-details view span {
    font-weight: bold;
    color: #007aff;
}

.debt-paystate {
    text-align: center;
}

.paystate {
    font-size: 28rpx;
    padding: 10rpx 16rpx;
    border-radius: 8rpx;
    font-weight: bold;
    text-align: center;
    min-width: 100rpx;
}

.paystate.unpaid {
    background: rgba(255, 92, 92, 0.1);
    color: #ff5c5c;
    border: 1rpx solid #ff5c5c;
}

.paystate.repaid {
    background: rgba(76, 175, 80, 0.1);
    color: #4caf50;
    border: 1rpx solid #4caf50;
}

.paystate.pending {
    background: rgba(255, 184, 77, 0.1);
    color: #ffb84d;
    border: 1rpx solid #ffb84d;
}

button {
    padding: 12rpx 24rpx;
    background: linear-gradient(90deg, #007aff, #005bb5);
    color: white;
    border: none;
    border-radius: 16rpx;
    cursor: pointer;
    font-size: 28rpx;
    transition: all 0.3s ease;
    margin-top: 20rpx;
}

button:hover {
    background: #005bb5;
    transform: scale(1.05);
}

button:disabled {
    background: #cccccc;
    cursor: not-allowed;
}

</style>
